#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""GIT util class

Defines the utility methods for Git.
"""

__author__ = 'Xin Zhou(zhounew@google.com)'

from git.json import git_json
from git.util import git_context

import re

class GitUtil(object):
  EMAIL_PATTERN = r'\w+(\.\w+)*@(\w+(\.\w+)+)'
  FEDERATED_DOMAINS = [#GMAIL
                       'gmail.com', 'googlemail.com',
                       #AOL
                       'aol.com', 'aim.com', 'netscape.net', 'cs.com',
                       'ygm.com', 'games.com', 'love.com', 'wow.com',
                       #Yahoo
                       'yahoo.com', 'rocketmail.com', 'ymail.com',
                       'y7mail.com', 'yahoo.com.au', 'yahoo.com.cn',
                       'yahoo.cn', 'yahoo.com.hk', 'yahoo.co.nz',
                       'yahoo.com.pk', 'yahoo.com.tw', 'kimo.com',
                       'bellsouth.net', 'ameritech.net', 'att.net',
                       'attworld.com', 'flash.net', 'nvbell.net',
                       'pacbell.net', 'prodigy.net', 'sbcglobal.net',
                       'snet.net', 'swbell.net', 'wans.net', 'btinternet.com',
                       'btopenworld.com', 'talk21.com', 'rogers.com',
                       'nl.rogers.com', 'demobroadband.com', 'xtra.co.nz',
                       'verizon.net',
                       #Hotmail
                       'hotmail.com', 'hotmail.co.uk', 'hotmail.fr',
                       'hotmail.it', 'live.com', 'msn.com'
                       ]
  
  @staticmethod
  def GetCurrentUrl(request):
    ''' Make sure this is the app engine request
    '''
    return request.url
  
  @staticmethod
  def SendError(error_msg):
    return error_msg
  
  @staticmethod
  def IsValidEmail(email):
    p = re.compile(GitUtil.EMAIL_PATTERN)
    if p.match(email):
        return True
    else:
        return False

  @staticmethod
  def GetEmailDomain(email):
    email = email.strip().lower()
    parts = email.split('@')
    if len(parts) > 1:
        return parts[1]
    return parts[0]
  
  @staticmethod
  def IsFederatedDomain(domain):
    if domain in GitUtil.FEDERATED_DOMAINS:
        return True
    return git_context.GitContext.GetDasherDomainChecker().IsDasherDomain(
        domain)
  
  @staticmethod
  def ToJSON(obj):
    return git_json.GitJson().dumps(obj);